<template>
	<view class="content">
		<!-- tabbar -->
		<view class="tabbar">
			<u-navbar :is-back="false" :is-fixed="false" :border-bottom="false">
				<view class="navbar-logo"><image src="../../static/logo.png" mode="aspectFit" class="image-logo"></image></view>
				<view class="navbar-user" slot="right" @click="toUser"><u-icon name="account" size="40" color="#d3daed"></u-icon></view>
			</u-navbar>
		</view>
    <!-- search -->
    <view class="q-title-search">
      <text class="text">行情</text>
      <view class="search">
        <u-search 
          placeholder="搜索币种" bg-color="none" 
          border-color="#d5cabb"
          shape="square" :show-action="false" 
          v-model="keyword"
          @change="onSearch">
        </u-search>
      </view>
    </view>
		<!-- container -->
    <view class="container">
      <view class="u-padding-left-20 u-padding-right-40">
        <u-tabs-swiper 
          ref="uTabs" 
          :list="list" 
          :current="current" 
          bar-width="70" 
          font-size="32"
          active-color="#c7ab6c"
          inactive-color="#979c95"
          bold item-width="130"
          @change="tabsChange">
        </u-tabs-swiper>
      </view>
      <swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
        <swiper-item class="swiper-item" v-for="(item, index) in list" :key="index">
          <scroll-view scroll-y style="height: 100vh;" @scrolltolower="onreachBottom">
            <view class="main-coinbase">
              <view class="list-item" v-for="(item, index) in (filterList || topSymbols)" :key="index" @click="toKline(item.symbol, item.id)">
                <coinbase-item
                  :name="item.title"
                  :value="topMakretMap[`market.${item.symbol}.detail`].tick ? topMakretMap[`market.${item.symbol}.detail`].tick.close : '0.00'"
                  :range="topMakretMap[`market.${item.symbol}.detail`].change"
                  :label="topMakretMap[`market.${item.symbol}.detail`].cny"
                  :hot="index == 0 || index == 1"
                  ></coinbase-item>
              </view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
	</view>
</template>

<script>
	
	import { CUser } from '@/common/cache/user.js';
	var cache_user = new CUser();
	
	export default {
		data() {
			return {
        keyword: '',
        list: [{
          name: '自选'
        },{
          name: '主板'
        },{
          name: '创新区'
        },{
          name: '开放区'
        }],
        current: 0, // tabs组件的current值，表示当前活动的tab选项
        swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
        
        topSymbols: [
        	{symbol: 'btcusdt', title: 'BTC/USDT'},
        	{symbol: 'ethusdt', title: 'ETH/USDT'},
        	{symbol: 'eosusdt', title: 'EOS/USDT'}
        ],
        topMakretMap: {
        	'market.btcusdt.detail': {},
        	'market.ethusdt.detail': {},
        	'market.eosusdt.detail': {},
        },
        filterList: false
			};
		},
    onShow() {

    },
    onLoad () {
		
			setTimeout(() =>{
				this.getData()
			}, 500);
			
			// 测试数据，3秒后自定义增加一个币种
			setTimeout(() => {
					  
              
              this.getListCoin().then((res) => {
                if (res.length) {
                  res.map((item) => {
                    let info = {
                      title: item.coinA + '/' + item.coinB, // 币种标题
                      change: ((item.coinAPrice - item.coinAOldPrice ) / item.coinAOldPrice  * 100).toFixed(2), // 浮动 比率
                      cny: item.coinAPrice,// 人民币价值
                      close: (item.coinAPrice / item.coinBPrice).toFixed(2), // 美元价值
                      id: item.id
                    }
                    this.onaAddData(info)
                  })
                }
              })
						
				
			     
			}, 100)

      
    },
		onUnload() {
			for(let i = 0; i < this.topSymbols.length; i++){
				let ch = `market.${this.topSymbols[i].symbol}.detail`
				let data = {
				  "unsub": ch,
				  "id": Date.now() + ""
				}
				this.$store.dispatch('WEBSOCKET_SEND', JSON.stringify(data))
				uni.$off(ch, (res) => {})
			}
		},
    methods: {
      onSearch () {
        if (this.$u.trim(this.keyword)) {
          this.filterList = this.topSymbols.filter((item) => {
            return item.title.toLocaleUpperCase().indexOf(this.$u.trim(this.keyword.toLocaleUpperCase())) != -1
          })
        } else {
          this.filterList = false
        }
      },
      getListCoin () {
        return new Promise((resolve) => {
          this.$api.http.get('assistance/tradinghall/getCoinList')
          .then(res => {
            resolve(res)
          });
        })
      },
      toKline (symbol, id) {
        this.$u.route({
          url: 'pages/public/kline',
          params: {
            symbol: symbol,
            id: id
          }
        })
      },
      /**
       * 固定增加数据
       * @param {Object} data - 需要传递的数据格式， 格式如下
       * {
          title: 'TEST/USDT', // 币种标题
          change: '1.2', // 浮动 比率
          cny: '999.99' ,// 人民币价值
          close: '132.09' // 美元价值
        }
       * @param {Boolean} type - 是否增加，默认增加，false为修改数据
       */
      onaAddData (data, type = true) {
        let _d = {symbol: data.title, title: data.title, id: data.id}
        if (type) this.topSymbols.unshift(_d);
        this.topMakretMap[`market.${data.title}.detail`] = {
          ch: `market.${data.title}.detail`,
          change: data.change,
          cny: data.cny,
          tick: {
            close: data.close
          }
        }
      },
      getData () {
        let $this = this
        for(let i = 0; i < this.topSymbols.length; i++){
          let ch = `market.${this.topSymbols[i].symbol}.detail`
          let data = {
            "sub": ch,
            "id": Date.now() + ""
          }
          this.$store.dispatch('WEBSOCKET_SEND', JSON.stringify(data))
          uni.$on(ch, (res) => {
            let d = res.data
            d.tick.close = Number(d.tick.close).toFixed(2)
            d.change = parseFloat((d.tick.close - d.tick.open) / d.tick.open * 100).toFixed(2);
            d.cny = parseFloat(d.tick.close * this.$store.state.UsdtPrice).toFixed(2)
            $this.topMakretMap[res.data.ch] = d
          })
        }
      },
      // tabs通知swiper切换
      tabsChange(index) {
        this.swiperCurrent = index;
      },
      // swiper-item左右移动，通知tabs的滑块跟随移动
      transition(e) {
        let dx = e.detail.dx;
        this.$refs.uTabs.setDx(dx);
      },
      // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
      // swiper滑动结束，分别设置tabs和swiper的状态
      animationfinish(e) {
        let current = e.detail.current;
        this.$refs.uTabs.setFinishCurrent(current);
        this.swiperCurrent = current;
        this.current = current;
      },
      // scroll-view到底部加载更多
      onreachBottom() {
        
      },
	  toUser() {
	  	uni.navigateTo({
	  		url: '../user/bussinessuser'
	  	});
	  },
    }
	}
</script>

<style lang="scss">
.swiper {
  height: calc(100vh - 84px - 50px);
  /* #ifdef APP-PLUS */
  height: calc(100vh - 80rpx - 44px - var(--status-bar-height));
  /* #endif */
}
.navbar-user {
  padding: 0 30rpx;
}
.main-coinbase {
  position: relative;
}
.navbar-logo {
	margin-left: 30rpx;
	.image-logo {
		width: 210rpx;
		height: 70rpx;
	}
}
.navbar-user {
	padding: 0 30rpx;
}
.q-title-search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 40rpx;
  .text {
    font-size: 40rpx;
    color: #c9be83;
  }
}
</style>
